package com.codebyorder.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codebyorder.entity.Content;
import com.codebyorder.entity.Doc;
import com.codebyorder.exception.BusinessException;
import com.codebyorder.exception.BusinessExceptionCode;
import com.codebyorder.mapper.ContentMapper;
import com.codebyorder.mapper.DocMapper;
import com.codebyorder.req.DocQueryReq;
import com.codebyorder.req.DocSaveReq;
import com.codebyorder.resp.CommonResp;
import com.codebyorder.resp.DocQueryResp;
import com.codebyorder.resp.PageResp;
import com.codebyorder.resp.WangEditorResp;
import com.codebyorder.service.DocService;
import com.codebyorder.service.WsService;
import com.codebyorder.util.CopyUtil;
import com.codebyorder.util.ImgToByte;
import com.codebyorder.util.RedisUtil;
import com.codebyorder.util.RequestContext;
import org.slf4j.MDC;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/doc")
public class DocController {

    @Resource
    private DocMapper docMapper;
    @Resource
    private ContentMapper contentMapper;
    @Resource
    private DocService docService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private WsService wsService;
//    @Resource
//    private RocketMQTemplate rocketMQTemplate;

    @GetMapping("/list")
    public CommonResp<PageResp<DocQueryResp>> list(@Valid DocQueryReq docQueryReq) {
        CommonResp<PageResp<DocQueryResp>> resp = new CommonResp<>();
        resp.setContent(docService.docToResp(docQueryReq));
        return resp;
    }

    @GetMapping("/all/{ebookIds}")
    public List<DocQueryResp> all(@PathVariable Long ebookIds) {
        QueryWrapper<Doc> queryWrap = new QueryWrapper<>();
        queryWrap.eq("ebook_id", ebookIds).orderByAsc("sort");
        List<Doc> docs = docMapper.selectList(queryWrap);
        return CopyUtil.copyList(docs, DocQueryResp.class);
    }

    @PostMapping("/save")
    @Transactional
    public CommonResp<Object> save(@Valid @RequestBody DocSaveReq docSaveReq) {
        Doc doc = CopyUtil.copy(docSaveReq, Doc.class);
        Content content = CopyUtil.copy(docSaveReq, Content.class);
        System.out.println("content:" + content);
        if (doc.getId() == null) {
            docMapper.insert(doc);
            content.setId(doc.getId());
            contentMapper.insert(content);
        } else {
            docMapper.updateById(doc);
            int count = contentMapper.updateById(content);
            if (count == 0) {
                contentMapper.insert(content);
            }
        }
        return new CommonResp<>();
    }

    @DeleteMapping("/delete/{ids}")
    public CommonResp<Object> delete(@PathVariable String ids) {
        List<String> idsStr = Arrays.asList(ids.split(","));
        docMapper.deleteBatchIds(idsStr);
        contentMapper.deleteBatchIds(idsStr);
        return new CommonResp<>();
    }

    @GetMapping("findContent/{id}")
    public String findContent(@PathVariable Long id) {
        Content content = contentMapper.selectById(id);
        docMapper.increaseViewCount(id);
        if (content == null) {
            return "";
        }
        return content.getContent();
    }

    @GetMapping("vote/{id}")
    public CommonResp<Object> vote(@PathVariable Long id) {

        String ip = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip, 3600 * 24)) {
            docMapper.increaseVoteCount(id);
        } else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }
        Doc docDB = docMapper.selectById(id);
        String logId = MDC.get("LOG_ID");
        wsService.sendInfo("【" + docDB.getName() + "】被点赞!", logId);
//        rocketMQTemplate.convertAndSend("VOTE_TOPIC", "【" + docDB.getName() + "】被点赞！");
        return new CommonResp<>();

    }
    @RequestMapping("upload-img")
    public Object uploadImg(MultipartFile file) throws IOException {
        return new WangEditorResp("0", Arrays.asList(ImgToByte.ImageToBase64(file)));
    }

}
